package com.shop.shoppingmall.util;

import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.presets.opencv_core;

import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 流水号生成规则(按默认规则递增，数字从1-99开始递增，数字到99，递增字母;位数不够增加位数)
 * A001
 * A001A002
 * @Author zhangdaihao
 *
 */
@Slf4j
public class YouBianCodeUtil {

	// 数字位数(默认生成3位的数字)

	private static final int numLength = 2;//代表数字位数

	public static final int zhanweiLength = 1+numLength;

	/**
	 * 根据前一个code，获取同级下一个code
	 * 例如:当前最大code为D01A04，下一个code为：D01A05
	 *
	 * @param code
	 * @return
	 */
	public static synchronized String getNextYouBianCode(String code) {
		String newcode = "";
		if (code == null || code =="") {
			String zimu = "A";
			String num = getStrNum(1);
			newcode = zimu + num;
		} else {
			String before_code = code.substring(0, code.length() - 1- numLength);
			String after_code = code.substring(code.length() - 1 - numLength,code.length());
			char after_code_zimu = after_code.substring(0, 1).charAt(0);
			Integer after_code_num = Integer.parseInt(after_code.substring(1));
//			org.jeecgframework.core.util.LogUtil.info(after_code);
//			org.jeecgframework.core.util.LogUtil.info(after_code_zimu);
//			org.jeecgframework.core.util.LogUtil.info(after_code_num);

			String nextNum = "";
			char nextZimu = 'A';
			// 先判断数字等于999*，则计数从1重新开始，递增
			if (after_code_num == getMaxNumByLength(numLength)) {
				nextNum = getNextStrNum(0);
			} else {
				nextNum = getNextStrNum(after_code_num);
			}
			// 先判断数字等于999*，则字母从A重新开始,递增
			if(after_code_num == getMaxNumByLength(numLength)) {
				nextZimu = getNextZiMu(after_code_zimu);
			}else{
				nextZimu = after_code_zimu;
			}

			// 例如Z99，下一个code就是Z99A01
			if ('Z' == after_code_zimu && getMaxNumByLength(numLength) == after_code_num) {
				newcode = code + (nextZimu + nextNum);
			} else {
				newcode = before_code + (nextZimu + nextNum);
			}
		}
		return newcode;

	}

	/**
	 * 根据父亲code,获取下级的下一个code
	 *
	 * 例如：父亲CODE:A01
	 *       当前CODE:A01B03
	 *       获取的code:A01B04
	 *
	 * @param parentCode   上级code
	 * @param localCode    同级code
	 * @return
	 */
	public static synchronized String getSubYouBianCode(String parentCode,String localCode) {
		if(localCode!=null && localCode!=""){

//			return parentCode + getNextYouBianCode(localCode);
			return getNextYouBianCode(localCode);

		}else{
			parentCode = parentCode + "A"+ getNextStrNum(0);
		}
		return parentCode;
	}



	/**
	 * 将数字前面位数补零
	 *
	 * @param num
	 * @return
	 */
	private static String getNextStrNum(int num) {
		return getStrNum(getNextNum(num));
	}

	/**
	 * 将数字前面位数补零
	 *
	 * @param num
	 * @return
	 */
	private static String getStrNum(int num) {
		String s = String.format("%0" + numLength + "d", num);
		return s;
	}

	/**
	 * 递增获取下个数字
	 *
	 * @param num
	 * @return
	 */
	private static int getNextNum(int num) {
		num++;
		return num;
	}

	/**
	 * 递增获取下个字母
	 *
	 * @param
	 * @return
	 */
	private static char getNextZiMu(char zimu) {
		if (zimu == 'Z') {
			return 'A';
		}
		zimu++;
		return zimu;
	}

	/**
	 * 根据数字位数获取最大值
	 * @param length
	 * @return
	 */
	private static int getMaxNumByLength(int length){
		if(length==0){
			return 0;
		}
		String max_num = "";
		for (int i=0;i<length;i++){
			max_num = max_num + "9";
		}
		return Integer.parseInt(max_num);
	}
	public static String[] cutYouBianCode(String code){
		if(code==null || StringUtil.isNullOrEmpty(code)){
			return null;
		}else{
			//获取标准长度为numLength+1,截取的数量为code.length/numLength+1
			int c = code.length()/(numLength+1);
			String[] cutcode = new String[c];
			for(int i =0 ; i <c;i++){
				cutcode[i] = code.substring(0,(i+1)*(numLength+1));
			}
			return cutcode;
		}

	}


	//快递物流 四川涪擎大数据技术有限公司
	private static String market(String num) {
		String host = "https://wuliu.market.alicloudapi.com";// 【1】请求地址 支持http 和 https 及 WEBSOCKET
		String path = "/kdi";  // 【2】后缀
		String appcode = "ef357d53f3e84c86bec9783747c920d7"; // 【3】开通服务后 买家中心-查看AppCode
		String no = num;// 【4】请求参数，详见文档描述
		String type = ""; //  【4】请求参数，不知道可不填 95%能自动识别
		String urlSend = host + path + "?no=" + no +"&type="+type;  // 【5】拼接请求链接
		try {
			URL url = new URL(urlSend);
			HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
			httpURLCon .setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
			int httpCode = httpURLCon.getResponseCode();
			if (httpCode == 200) {
				String json = read(httpURLCon.getInputStream());
				System.out.println("正常请求计费(其他均不计费)");
				System.out.println("获取返回的json:");
				return json;
			} else {
				Map<String, List<String>> map = httpURLCon.getHeaderFields();
				String error = map.get("X-Ca-Error-Message").get(0);
				if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
					return "AppCode错误 ";
				} else if (httpCode == 400 && error.equals("Invalid Url")) {
					return "请求的 Method、Path 或者环境错误";
				} else if (httpCode == 400 && error.equals("Invalid Param Location")) {
					return "参数错误";
				} else if (httpCode == 403 && error.equals("Unauthorized")) {
					return "服务未被授权（或URL和Path不正确）";
				} else if (httpCode == 403 && error.equals("Quota Exhausted")) {
					return "套餐包次数用完 ";
				} else {
					return "参数名错误 或 其他错误"+error;
				}
			}

		} catch (MalformedURLException e) {
			return "URL格式错误";
		} catch (UnknownHostException e) {
			return "URL地址错误";
		} catch (Exception e) {
			// 打开注释查看详细报错异常信息
			e.printStackTrace();
			return "打开注释查看详细报错异常信息";
		}
	}

	private static String read(InputStream is) throws IOException {
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line = null;
		while ((line = br.readLine()) != null) {
			line = new String(line.getBytes(), "utf-8");
			sb.append(line);
		}
		br.close();
		return sb.toString();
	}


	//济南联卓信息技术有限公司
	private static String market1(String num) throws IOException {
		String host = "https://qyexpress.market.alicloudapi.com";
		String path = "/composite/queryexpress";
		String appcode = "c6f01f6d843f49fc8a48fbb5ac5d5136";
		String mobile ="";
		String number = num;
		String urlSend = host + path + "?mobile=" + mobile +"&number="+ number;
		URL url = new URL(urlSend);
		HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
		httpURLCon .setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
		int httpCode = httpURLCon.getResponseCode();
		String json = read(httpURLCon.getInputStream());
		return json;
	}

	private static void descartes(List<List<String>> dimvalue, List<List<String>> result, int layer, List<String> curList) {
		if (layer < dimvalue.size() - 1) {
			if (dimvalue.get(layer).size() == 0) {
				descartes(dimvalue, result, layer + 1, curList);
			} else {
				for (int i = 0; i < dimvalue.get(layer).size(); i++) {
					List<String> list = new ArrayList<String>(curList);
					list.add(dimvalue.get(layer).get(i));
					descartes(dimvalue, result, layer + 1, list);
				}
			}
		} else if (layer == dimvalue.size() - 1) {
			if (dimvalue.get(layer).size() == 0) {
				result.add(curList);
			} else {
				for (int i = 0; i < dimvalue.get(layer).size(); i++) {
					List<String> list = new ArrayList<String>(curList);
					list.add(dimvalue.get(layer).get(i));
					result.add(list);
				}
			}
		}
	}
	public static String addDateMinut(Date date, int hour){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("front:" + format.format(date)); //显示输入的日期
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.YEAR, hour);// 24小时制
		date = cal.getTime();
		System.out.println("after:" + format.format(date));  //显示更新后的日期
		cal = null;
		return format.format(date);

	}
	public static   String getABCDCode(String idValue){
		char[] chars=idValue.toCharArray();
		if (chars[3]==57){
			chars[3]+=8;
		}else if (chars[3]<90){
			chars[3]++;
		} else {
			if (chars[2]==57){
				chars[2]+=8;
				chars[3]=48;
			}else if (chars[2]<90) {
				chars[2]++;
				chars[3] = 48;
			}else {
				if (chars[1]==57){
					chars[1]+=8;
					chars[2]=48;
					chars[3]=48;
				}else if (chars[1]<90){
					chars[1]++;
					chars[2]=48;
					chars[3]=48;
				}else {
					if (chars[0]==57) {
						chars[0] += 8;
						chars[1] = 48;
						chars[2] = 48;
						chars[3] = 48;
					}else if (chars[0]<90){
						chars[0] ++;
						chars[1] = 48;
						chars[2] = 48;
						chars[3] = 48;
					}else {
						System.out.print("编码用完了");
					}
				}
			}
		}
		StringBuffer sbu = new StringBuffer();
		for (int i = 0; i < chars.length; i++) {
			sbu.append(chars[i]);
		}
		return sbu.toString();
	}
	public static void main(String[] args) throws ParseException, IOException {
		String code = oConvertUtils.randomGen(16);
		System.out.println(code);

	}
}
